'use strict';
import XPay from 'react-native-puti-pay';
import * as IaPay from 'react-native-iap';

const result_success = { msg: '支付成功!', code: StatusCode.SUCCESS_CODE }
const result_fail = { msg: '支付失败!', code: StatusCode.FAIL_CODE }
const result_cancel = { msg: '取消支付!', code: StatusCode.FAIL_CODE }

class PayManager {

    // type:'wxpay'  alipay   iapay
    static async pay(type, data) {
        if (type === 'wxpay') {
            const res = await this.wxPay(data)
            if (res.errCode == StatusCode.SUCCESS_CODE) {
                return Promise.resolve(result_success)
            } else {
                return Promise.resolve(result_fail)
            }
        } else if (type === 'alipay') {
            const res = await this.aliPay(data)
            if (res.resultStatus == '6001') {
                return Promise.resolve(result_cancel)
            } else if (res.resultStatus == '9000') {
                const result = JSON.parse(res.result)
                if (result.alipay_trade_app_pay_response.code == 10000) {
                    return Promise.resolve(result_success)
                } else {
                    return Promise.resolve(result_fail)
                }
            } else {
                return Promise.resolve(result_fail)
            }
        } else if (type === 'iapay') {
            const res = await this.iaPay(data)
            if (res) {
                return Promise.resolve(result_success)
            } else {
                return Promise.resolve(result_fail)
            }
        }
    }

    static wxPay(data) {
        return new Promise((resolve) => {
            const wxData = {
                partnerId: data.partnerid,
                prepayId: data.prepayid,
                packageValue: data.package,
                nonceStr: data.noncestr,
                timeStamp: data.timestamp,
                sign: data.sign,
            }
            XPay.wxPay(wxData, (res) => {
                // console.log('微信支付', res)
                resolve(res)
            })
        })
    }

    static aliPay(data) {
        return new Promise((resolve) => {
            XPay.alipay(data, (res) => {
                // console.log('支付宝支付', res)
                resolve(res)
            })
        })
    }

    static async iaPay(data) {
        const purchase = await IaPay.buyProduct(data.id);
        // console.log('iaPay', purchase)
        return purchase
    }


}

export default PayManager